package com.boang.jdbc;

import java.sql.*;

/*
  @author: 13813
  @date: 2024/12/9 17:07
*/
public class JdbcDemo02 {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        int claId = addCla("73期");
        Student student = new Student("小明明", claId);
        addStu(student);
//        remove(22);

    }

    private static int addStu(Student student) throws SQLException, ClassNotFoundException {
        //增 班级表
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db62", "root", "123456");
        PreparedStatement preparedStatement = connection.prepareStatement("insert into student(name,cla_id)values(?,?)");
        preparedStatement.setString(1, student.getName());
        preparedStatement.setInt(2, student.getClaId());
        int i = preparedStatement.executeUpdate();
        return 0;
    }

    private static int addCla(String name) throws SQLException, ClassNotFoundException {
        //增 班级表
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db62", "root", "123456");
        PreparedStatement preparedStatement = connection.prepareStatement("insert into cla(name)values(?)");
        preparedStatement.setString(1, name);
        int i = preparedStatement.executeUpdate();

        PreparedStatement prepared = connection.prepareStatement("select last_insert_id()");
        ResultSet resultSet = prepared.executeQuery();

        while (resultSet.next()) {
            int claId = resultSet.getInt(1);
            return claId;
        }
        return 0;
    }

    private static void remove(int id) throws SQLException {
        //删 班级表
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db62", "root", "123456");
        PreparedStatement preparedStatement = connection.prepareStatement("delete from cla where id = ?");
        preparedStatement.setInt(1, id);
        preparedStatement.executeUpdate();
    }
}
